package com.web.kdl.controller.video;
import com.web.kdl.common.result.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;

/**
 * @Author： shulibin
 * @Date： 2025/8/1 16:48
 * @Describe：
 */
@RestController
@RequestMapping("/api/videos")
public class VideoController {

    private static final Logger log = LoggerFactory.getLogger(VideoController.class);
    @Value("${file.upload-path}")
    private String uploadPath;


    // 固定文件名（确保唯一）
    private static final String UNIQUE_FILENAME = "current_video.mp4";

    @PostMapping("/upload")
    public CommonResult<String> uploadVideo(
            @RequestParam("file") MultipartFile file) throws IOException {

        // 1. 基础验证
        if (file.isEmpty()) {
            return CommonResult.error("请选择有效的视频文件");
        }

        try {
            Path dirPath = Paths.get(uploadPath);
            Path filePath = dirPath.resolve(UNIQUE_FILENAME);

            // 3. 自动清理目录（确保只存在一个文件）
            cleanDirectory(dirPath);

            // 4. 保存新文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            return CommonResult.success("视频已成功替换");

        } catch (IOException e) {
            log.error("上传失败: {}", e.getMessage(), e);
            throw new IOException("视频保存失败", e);
        }
    }

    // 视频类型验证方法
    private boolean isVideoFile(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null && contentType.startsWith("video/");
    }

    // 清理目录方法
    private void cleanDirectory(Path dirPath) throws IOException {
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
            return;
        }

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath)) {
            for (Path path : stream) {
                if (!Files.isDirectory(path)) {
                    Files.delete(path);
                }
            }
        }
    }


}
